<script lang="ts" setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {useRoute} from "vue-router";
import router from "@/router";
import IngredientItem from "@/components/IngredientItem.vue";
import {addNewPerfumeInCart, parseIngredient} from '@/util/checkHasStore'
import {useToast} from 'vue-toast-notification';
import 'vue-toast-notification/dist/theme-sugar.css';
import CommentItem from "@/components/CommentItem.vue";

const $toast = useToast();//消息提示栏
const perfumeInfo = ref(Object)

const route = useRoute()
const isBad = ref(false)
const perfumeId = ref(0)
const initData = () => {
  axios.post(`/api/perfume/get/${perfumeId.value}`, {}, {
    headers: {
      token: localStorage.getItem("wiki-auth-token")
    }
  })
      .then(res => {
        // console.log(res)
        if (res.data.success) {
          const msg = res.data.message
          msg.ingredientVos = parseIngredient(msg.ingredientVos)
          // console.log(msg)
          perfumeInfo.value = msg
        } else {
          isBad.value = true
          setTimeout(() => {
            router.push('/')
          }, 1000)
        }
      })
}
onMounted(() => {
  perfumeId.value = route.query.id
  console.log(route.query.id)

  setTimeout(() => (
      initData()
  ))
})
const isLogin = ref(false)
const checkLogin = () => {
  if (localStorage.getItem("wiki-auth-token")) {
    const token = localStorage.getItem("wiki-auth-token")
    axios.post("/api/auth/check", {}, {  // 这里传递空对象作为请求体
      headers: {
        token: token  // 使用token作为请求头
      }
    }).then(res => {
      console.log(res);
      const msg = res.data.message;
      if (res.data.success) {
        // 成功的处理逻辑
        localStorage.setItem("wiki-auth-token", msg)
        isLogin.value = true;
      }
    })
  } else {
    isLogin.value = false
  }

}
checkLogin()
const buyIt = () => {
  if (isLogin.value) {
    addNewPerfumeInCart({
      name: perfumeInfo.value.name,
      count: 1, price: perfumeInfo.value.price, id: perfumeInfo.value.perfumeId, img: perfumeInfo.value.img
    })
  } else {
    $toast.open({
      message: "请先登录，在添加购物车",
      type: "error",
      position: "bottom-right"
    })
  }

}
const createOrderInfo = () => {
  if (!address.value) {
    $toast.open({
      message: "请输入收货地址",
      type: "warning",
      position: "bottom-right"
    })
    return
  }
  if (count.value < 1) {
    $toast.open({
      message: "购买数量异常",
      type: "error",
      position: "bottom-right"
    })
    return
  }
  let url = '/api/order/create';

  // 构建 orderRecepts 数组
  let arr = []
  arr.push({
    id: perfumeId.value,
    count: count.value
  })
  const data = {
    orderReceipts: arr,
    address: address.value
  }
  axios.post(url, data, {
    headers: {
      token: localStorage.getItem("wiki-auth-token")
    }
  })
      .then(res => {
        console.log(res);
        if (res.data.success) {
          $toast.open({
            message: "购买成功",
            type: "success",
            position: "bottom-right"
          })
          prompt.value = false
          router.push("/perfume")
        } else {
          $toast.open({
            message: "购买失败",
            type: "error",
            position: "bottom-right"
          })
          prompt.value = false
        }
      })
      .catch(error => {
        $toast.open({
          message: "购买异常",
          type: "warning",
          position: "bottom-right"
        })
        prompt.value = false
      });
}
const nowBuy = () => {
  if (!isLogin.value) {
    $toast.open({
      message: "请先登录再进行购买操作",
      type: "warning",
      position: "bottom-right"
    })
    return;
  }
  prompt.value = true
}
const count = ref(1)
const prompt = ref(false)
const address = ref('')
const editComment = () => {
  if(!isLogin.value){
    $toast.open({
      message: "请先登录再进行评论",
      type: "warning",
      position: "bottom-right"
    })
    return;
  }
  editCommentFlag.value = true
}
const createComment = () => {
  if(!isLogin.value){
    $toast.open({
      message: "请先登录再进行评论",
      type: "warning",
      position: "bottom-right"
    })
    return;
  }
  axios.post("/api/perfume/comment",{
    perfumeId:perfumeId.value,
    context: comment.value
  },{
    headers:{
      token:localStorage.getItem("wiki-auth-token")
    }
  }).then(res=>{
    console.log(res)
    if(res.data.success){
      $toast.open({
        message: "评论成功",
        type: "success",
        position: "bottom-right"
      })
      comment.value =''
      editCommentFlag.value = false
      initData()
    }else{
      $toast.open({
        message: res.data.message,
        type: "error",
        position: "bottom-right"
      })
      editCommentFlag.value = false
    }
  })
}
const comment = ref('')
const editCommentFlag = ref(false)
const commentRemove = (index: number, newStatus: boolean)=>{
  initData()
}
</script>

<template>
  <div class="perfume-detail-main">
    <q-dialog v-model="prompt" persistent>
      <q-card style="min-width: 350px">
        <q-card-section>
          <div class="text-h6">订单信息</div>
        </q-card-section>
        <q-card-section class="q-pt-none">
          <q-input v-model="address" autofocus dense hint="请输入你的收货地址" label="地址"/>
        </q-card-section>
        <q-card-section class="q-pt-none">
          香水名称：${{ perfumeInfo.name }}
        </q-card-section>
        <q-card-section class="q-pt-none">
          价格：{{ perfumeInfo.price }}
        </q-card-section>
        <q-card-section class="q-pt-none" style="display: flex;align-items: center">
          图片信息：<img :src="perfumeInfo.img" alt="" style="height: 60px">
        </q-card-section>
        <q-card-section class="q-pt-none">
          <q-input
              v-model.number="count"
              filled
              label="购买数量"
              style="width: 100%"
              type="number"
          >
            <q-tooltip>
              数量不可小于0
            </q-tooltip>
          </q-input>
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn v-close-popup flat label="取消购买"/>
          <q-btn flat label="立即购买" @click="createOrderInfo"/>
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog v-model="editCommentFlag" persistent>
      <q-card style="min-width: 450px">
        <q-card-section>
          <div class="text-h6">评论内容</div>
        </q-card-section>
        <q-card-section class="q-pt-none">
          <q-editor v-model="comment" min-height="15rem" style="width: 500px"
                    flat
                    content-class="bg-amber-3"
                    toolbar-text-color="white"
                    toolbar-toggle-color="yellow-8"
                    toolbar-bg="primary"
                    :toolbar="[
        ['italic', 'underline'],
        [{
          label: $q.lang.editor.formatting,
          icon: $q.iconSet.editor.formatting,
          list: 'no-icons',
          options: ['p', 'h3', 'h4', 'h5', 'h6', 'code']
        }]
      ]"
          />
<!--          <q-input v-model="comment" autofocus dense hint="请输入你的评论内容" label="评论内容" type="textarea"/>-->
        </q-card-section>
        <q-card-actions align="right" class="text-primary">
          <q-btn v-close-popup flat label="取消评论"/>
          <q-btn flat label="立即评论" @click="createComment"/>
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-card v-show="isBad" style="width: 100vw">
      <q-item>
        <q-item-section avatar style="height: 20vh">
          <q-skeleton type="QAvatar"/>
        </q-item-section>

        <q-item-section style="height: 60vh">
          <q-item-label>
            <q-skeleton type="text"/>
          </q-item-label>
          香水信息异常，即将返回首页
          <q-item-label caption>
            <q-skeleton type="text"/>
          </q-item-label>
        </q-item-section>
      </q-item>
      <q-skeleton height="200px" square/>

      <q-card-actions align="right" class="q-gutter-md">
        <q-skeleton type="QBtn"/>
        <q-skeleton type="QBtn"/>
      </q-card-actions>
    </q-card>
    <div class="perfume-title">
      {{ perfumeInfo.name }}
    </div>
    <div class="perfume-detail-group" style="margin-left: 10vw;margin-right: 10vw;height: 500px">
      <q-img
          :src="perfumeInfo.img"
          style="width: 300px;max-height: 500px;margin-right: 5vw;"
      />
      <div class="detail-info">
        <div class="detail-info-item">
          <div class="detail-info-item-title">Brand</div>
          <div class="detail-info-item-context"> {{ perfumeInfo.brandText }}</div>
        </div>
        <div class="detail-info-item">
          <div class="detail-info-item-title">适用性别</div>
          <div class="detail-info-item-context"> {{ perfumeInfo.sex }}</div>
        </div>
        <div class="detail-info-item">
          <div class="detail-info-item-title">香调</div>
          <div class="detail-info-item-context"> {{ perfumeInfo.fragranceNote }} | 亚科 {{ perfumeInfo.smell }}</div>
        </div>
        <div class="detail-info-item">
          <div class="detail-info-item-title">上线年份</div>
          <div class="detail-info-item-context"> {{ perfumeInfo.year }}</div>
        </div>
        <div class="detail-info-item">
          <div class="detail-info-item-title">价格</div>
          <div class="detail-info-item-context"> ${{ perfumeInfo.price }}</div>
        </div>
        <div style="display: flex;width: 90%;margin-top: 20px;">
          <q-btn color="amber-9" icon="shopping_cart" style="z-index: 2;flex:1" @click="buyIt">
            <q-tooltip>加入购物车</q-tooltip>
          </q-btn>
          <q-btn color="red-12" icon="shopping_bag" style="z-index: 2;flex:1" @click="nowBuy">
            <q-tooltip>立即购买</q-tooltip>
          </q-btn>
        </div>
      </div>
    </div>
    <div class="ingredient-info">
      <div class="title">原料</div>
      <div class="ingredient-group">
        <IngredientItem
            v-for="(item,index) in perfumeInfo.ingredientVos"
            :key="index"
            :fragrance-noted-id="item.fragranceNoteId"
            :img="item.img"
            :ingredient-id="item.ingredientId"
            :is-add="item.isAdd"
            :name="item.name"
        />
      </div>
    </div>
    <div class="ingredient-info" style="margin-bottom: 10vh">
      <div style="display:flex;justify-content: space-between">
        <div class="title">用户评论</div>
        <div class="title cursor-pointer" @click="editComment">评论撰写</div>
      </div>
      <div style="display:flex;flex-direction: column">
        <CommentItem
            v-for="(item,index) in perfumeInfo.perfumeCommentInfoVos"
            :key="index"
            :context="item.context" :input-time="item.inputTime"
            :perfume-comment-id="item.perfumeCommentId" :user-info="item.userInfo"
            @updateCommentRemove="commentRemove(index, $event)"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.perfume-detail-main {
  width: 100vw;
  display: flex;
  height: 100vh;
  overflow-y: auto;
  background-color: #fff;
  z-index: 100000;
  flex-direction: column;

  .perfume-title {
    font-size: 40px;
    margin-top: 2vh;
    margin-bottom: 4vh;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .perfume-detail-group {
    width: 80vw;
    display: flex;
    justify-content: space-around;
    align-items: center;

    .detail-info {
      display: flex;
      flex-direction: column;
      flex: 1;
      justify-content: space-around;
      max-width: 600px;

      &-item {
        max-width: 500px;
        display: flex;
        flex-direction: column;
        margin-top: 5px;
        padding-bottom: 5px;
        border-bottom: 1px solid gray;

        &-title {
          font-size: 14px;
          color: gray;
        }

        &-context {
          font-size: 18px;
        }
      }
    }

  }

  .ingredient-info {
    display: flex;
    flex-direction: column;
    width: 90vw;
    margin-left: 5vw;
    margin-right: 5vw;

    .title {
      font-size: 20px;
    }

    .ingredient-group {
      display: flex;
      flex-wrap: wrap;
    }
  }
}
</style>